package com.lottery.im.module.tim.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.LayoutRes;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.module.tim.face.DefaultGifEmoji;
import com.lottery.im.module.tim.face.EqualHeightSpan;
import com.lottery.im.module.tim.message.CustomMessageType;
import com.lottery.im.module.tim.utils.EmoticonUtil;
import com.lottery.im.module.tim.viewfeatures.ChatView;
import com.lottery.im.util.SPUtils;
import com.lottery.im.widget.dialog.BottomSelectDialog;
import com.lottery.im.widget.indicator.CirclePageIndicator;
import com.sunhapper.spedittool.view.SpEditText;
import com.tbruyelle.rxpermissions2.RxPermissions;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 聊天界面输入控件
 */
public class ChatInput extends RelativeLayout implements TextWatcher, View.OnClickListener {

  private static final int DISTANCE_Y_CANCEL = 50;

  private ImageButton btnAdd, btnSend, btnVoice, btnKeyboard, btnEmotion;
  private SpEditText editText;
  private boolean isSendVisible, isHoldVoiceBtn, isEmoticonReady, isCancel;
  private InputMode inputMode = InputMode.NONE;
  private ChatView chatView;
  private LinearLayout morePanel, textPanel;
  private TextView voicePanel;
  private LinearLayout emoticonPanel;
  private final int REQUEST_CODE_ASK_PERMISSIONS = 100;

  private LinearLayout mBtnNamecard;

  private CommonTabLayout mTabLayout;
  private ViewPager mViewPager;
  private CirclePageIndicator mIndicator;
  private List<GridView> mGridViews = new ArrayList<>();
  private FaceViewPagerAdapter mFaceViewPagerAdapter;

  public static int item_grid_num = 21;//每一页中GridView中item的数量
  public static int number_columns = 7;

  private List<String> iconNames = new ArrayList();

  private int[] iconN = {
      R.drawable.icon_face_n, R.drawable.icon_face_image_n, R.drawable.icon_ajmd_s_normal,
      R.drawable.icon_lt_s_normal,
      R.drawable.icon_xxy_s_normal
  };

  private int[] iconS = {
      R.drawable.icon_face_s, R.drawable.icon_face_image_s, R.drawable.icon_ajmd_s_highlighted,
      R.drawable.icon_lt_s_highlighted,
      R.drawable.icon_xxy_s_highlighted
  };

  public ChatInput(Context context, AttributeSet attrs) {
    super(context, attrs);
    LayoutInflater.from(context).inflate(R.layout.chat_input, this);
    initView();
  }

  private void initView() {
    textPanel = findViewById(R.id.text_panel);
    btnAdd = findViewById(R.id.btn_add);
    btnAdd.setOnClickListener(this);
    btnSend = findViewById(R.id.btn_send);
    btnSend.setOnClickListener(this);
    btnVoice = findViewById(R.id.btn_voice);
    btnVoice.setOnClickListener(this);
    btnEmotion = findViewById(R.id.btnEmoticon);
    btnEmotion.setOnClickListener(this);
    morePanel = findViewById(R.id.morePanel);
    LinearLayout BtnImage = findViewById(R.id.btn_photo);
    BtnImage.setOnClickListener(this);
    LinearLayout BtnPhoto = findViewById(R.id.btn_image);
    BtnPhoto.setOnClickListener(this);
    LinearLayout btnVideo = findViewById(R.id.btn_video);
    btnVideo.setOnClickListener(this);
    LinearLayout btnMoney = findViewById(R.id.btn_money);
    btnMoney.setOnClickListener(this);
    mBtnNamecard = findViewById(R.id.btn_namecard);
    mBtnNamecard.setOnClickListener(this);
    setSendBtn();
    btnKeyboard = findViewById(R.id.btn_keyboard);
    btnKeyboard.setOnClickListener(this);
    voicePanel = findViewById(R.id.voice_panel);
    voicePanel.setOnTouchListener(new OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
            isHoldVoiceBtn = true;
            updateVoiceView();
            break;
          case MotionEvent.ACTION_MOVE:
            if (isHoldVoiceBtn) {
              chatView.wantToCancel(wantToCancel((int) event.getX(), (int) event.getY()));
            }
            break;
          case MotionEvent.ACTION_UP:
            isHoldVoiceBtn = false;
            updateVoiceView();
            break;
        }
        return true;
      }
    });
    editText = findViewById(R.id.input);
    editText.addTextChangedListener(this);
    editText.setOnFocusChangeListener(new OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
          updateView(InputMode.TEXT);
        }
      }
    });
    isSendVisible = editText.getText().length() != 0;
    emoticonPanel = findViewById(R.id.emoticonPanel);

    mTabLayout = findViewById(R.id.tabLayout);
    mViewPager = findViewById(R.id.view_pager);
    mIndicator = findViewById(R.id.indicator);
  }

  /*
   *  初始化 tab
   * */
  private void initTabs() {
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    for (int i = 0; i < iconN.length; i++) {
      final int position = i;
      tabEntities.add(new CustomTabEntity() {
        @Override public String getTabTitle() {
          return "";
        }

        @Override public int getTabSelectedIcon() {
          return iconS[position];
        }

        @Override public int getTabUnselectedIcon() {
          return iconN[position];
        }
      });
    }
    mTabLayout.setTabData(tabEntities);
    mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {
        setFaceLayout(position);
      }

      @Override public void onTabReselect(int position) {

      }
    });
  }

  private void updateView(InputMode mode) {
    if (mode == inputMode) return;
    leavingCurrentState();
    switch (inputMode = mode) {
      case MORE:
        morePanel.setVisibility(VISIBLE);
        break;
      case TEXT:
        if (editText.requestFocus()) {
          InputMethodManager imm =
              (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
        }
        break;
      case VOICE:
        voicePanel.setVisibility(VISIBLE);
        textPanel.setVisibility(GONE);
        btnVoice.setVisibility(GONE);
        btnKeyboard.setVisibility(VISIBLE);
        break;
      case EMOTICON:
        if (!isEmoticonReady) {
          //prepareEmoticon();
          intList();
        }
        emoticonPanel.setVisibility(VISIBLE);
        break;
    }
  }

  private void leavingCurrentState() {
    switch (inputMode) {
      case TEXT:
        View view = ((Activity) getContext()).getCurrentFocus();
        InputMethodManager imm =
            (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        editText.clearFocus();
        break;
      case MORE:
        morePanel.setVisibility(GONE);
        break;
      case VOICE:
        voicePanel.setVisibility(GONE);
        textPanel.setVisibility(VISIBLE);
        btnVoice.setVisibility(VISIBLE);
        btnKeyboard.setVisibility(GONE);
        break;
      case EMOTICON:
        emoticonPanel.setVisibility(GONE);
    }
  }

  private void updateVoiceView() {
    if (isHoldVoiceBtn) {
      voicePanel.setText(getResources().getString(R.string.chat_release_send));
      voicePanel.setBackground(getResources().getDrawable(R.drawable.btn_voice_pressed));
      chatView.startSendVoice();
    } else {
      voicePanel.setText(getResources().getString(R.string.chat_press_talk));
      voicePanel.setBackground(getResources().getDrawable(R.drawable.btn_voice_normal));
      chatView.endSendVoice(isCancel);
    }
  }

  // 判断是否想去取消
  private boolean wantToCancel(int x, int y) {
    // TODO Auto-generated method stub

    if (x < 0 || x > getWidth()) {// 判断是否在左边，右边，上边，下边
      isCancel = true;
      return true;
    }
    if (y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
      isCancel = true;
      return true;
    }
    isCancel = false;
    return false;
  }

  /**
   * 关联聊天界面逻辑
   */
  public void setChatView(ChatView chatView) {
    this.chatView = chatView;
  }

  /**
   * This method is called to notify you that, within <code>s</code>,
   * the <code>count</code> characters beginning at <code>start</code>
   * are about to be replaced by new text with length <code>after</code>.
   * It is an error to attempt to make changes to <code>s</code> from
   * this callback.
   */
  @Override
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {

  }

  /**
   * This method is called to notify you that, within <code>s</code>,
   * the <code>count</code> characters beginning at <code>start</code>
   * have just replaced old text that had length <code>before</code>.
   * It is an error to attempt to make changes to <code>s</code> from
   * this callback.
   */
  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {
    isSendVisible = s != null && s.length() > 0;
    setSendBtn();
    if (isSendVisible) {
      chatView.sending();
    }
    chatView.onTextChanged(s, start, before, count);
  }

  /**
   * This method is called to notify you that, somewhere within
   * <code>s</code>, the text has been changed.
   * It is legitimate to make further changes to <code>s</code> from
   * this callback, but be careful not to get yourself into an infinite
   * loop, because any changes you make will cause this method to be
   * called again recursively.
   * (You are not told where the change took place because other
   * afterTextChanged() methods may already have made other changes
   * and invalidated the offsets.  But if you need to know here,
   * you can use {@link Spannable#setSpan} in {@link #onTextChanged}
   * to mark your place and then look up from here where the span
   * ended up.
   */
  @Override
  public void afterTextChanged(Editable s) {

  }

  private void setSendBtn() {
    if (isSendVisible) {
      btnAdd.setVisibility(GONE);
      btnSend.setVisibility(VISIBLE);
    } else {
      btnAdd.setVisibility(VISIBLE);
      btnSend.setVisibility(GONE);
    }
  }

  private void prepareEmoticon() {
    if (emoticonPanel == null) return;
    for (int i = 0; i < 5; ++i) {
      LinearLayout linearLayout = new LinearLayout(getContext());
      linearLayout.setLayoutParams(
          new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f));
      for (int j = 0; j < 7; ++j) {

        try {
          AssetManager am = getContext().getAssets();
          final int index = 7 * i + j;
          InputStream is = am.open(String.format("emoticon/%d.gif", index));
          Bitmap bitmap = BitmapFactory.decodeStream(is);
          Matrix matrix = new Matrix();
          int width = bitmap.getWidth();
          int height = bitmap.getHeight();
          matrix.postScale(3.5f, 3.5f);
          final Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
              width, height, matrix, true);
          ImageView image = new ImageView(getContext());
          image.setImageBitmap(resizedBitmap);
          image.setLayoutParams(
              new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                  1f));
          linearLayout.addView(image);
          image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
              String content = String.valueOf(index);
              SpannableString str = new SpannableString(String.valueOf(index));
              ImageSpan span = new ImageSpan(getContext(), resizedBitmap, ImageSpan.ALIGN_BASELINE);
              str.setSpan(span, 0, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
              editText.append(str);
            }
          });
          is.close();
        } catch (IOException e) {

        }
      }
      emoticonPanel.addView(linearLayout);
    }
    isEmoticonReady = true;
  }

  private void intList() {
    initTabs();
    mFaceViewPagerAdapter = new FaceViewPagerAdapter();
    mViewPager.setAdapter(mFaceViewPagerAdapter);
    mIndicator.setViewPager(mViewPager);
    setFaceLayout(0);
    isEmoticonReady = true;
  }

  private void setFaceLayout(int position) {

    mGridViews.clear();
    iconNames.clear();

    @LayoutRes
    int layoutRes;

    if (position == 0) {
      item_grid_num = 21;//每一页中GridView中item的数量
      number_columns = 7;
      layoutRes = R.layout.item_gridview_face;
      // 添加默认表情图标
      for (int i = 0; i < 35; i++) {
        iconNames.add("emoticon" + i + ".gif");
      }
    } else {
      item_grid_num = 10;//每一页中GridView中item的数量
      number_columns = 5;
      layoutRes = R.layout.item_gridview_face_custom;

      if (position == 1) {

        String facePaths =
            (String) SPUtils.get(MyApplication.getInstance(), SpKeyConstant.FACE_IMGAE_PATH_KEY,
                "");
        if (!TextUtils.isEmpty(facePaths)) {
          List<String> paths = Arrays.asList(facePaths.split(","));
          for (String path : paths) {
            iconNames.add(path);
          }
        }
      } else if (position == 2) {
        for (int i = 1; i < 51; i++) {
          if (i < 10) {
            iconNames.add("sx00" + i + ".gif");
          } else {
            iconNames.add("sx0" + i + ".gif");
          }
        }
      } else if (position == 3) {
        for (int i = 1; i < 21; i++) {
          if (i < 10) {
            iconNames.add("lt00" + i + ".png");
          } else {
            iconNames.add("lt0" + i + ".png");
          }
        }
      } else if (position == 4) {
        for (int i = 1; i < 41; i++) {
          if (i < 10) {
            iconNames.add("xxy00" + i + ".png");
          } else {
            iconNames.add("xxy0" + i + ".png");
          }
        }
      }
    }

    //计算viewpager一共显示几页
    int pageSize = iconNames.size() % item_grid_num == 0
        ? iconNames.size() / item_grid_num
        : iconNames.size() / item_grid_num + 1;
    for (int i = 0; i < pageSize; i++) {
      GridView gridView = new GridView(getContext());
      FaceGridViewAdapter adapter =
          new FaceGridViewAdapter(iconNames, i, layoutRes);
      gridView.setNumColumns(number_columns);
      gridView.setAdapter(adapter);
      gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          onFaceClick(position);
        }
      });

      gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
          onFaceLongClick(position);
          return true;
        }
      });

      mGridViews.add(gridView);
    }
    mFaceViewPagerAdapter.add(mGridViews);
    mViewPager.setCurrentItem(0);
    mIndicator.notifyDataSetChanged();
  }

  private void onFaceClick(int position) {
    int currentTab = mTabLayout.getCurrentTab();
    int currentItem = mViewPager.getCurrentItem();

    if (currentTab == 0) {
      //  默认表情点击
      //try {
      //  AssetManager am = getContext().getAssets();
      //  final int index = currentItem * item_grid_num + position;
      //  InputStream is = am.open(String.format("emoticon/%d.gif", index));
      //  Bitmap bitmap = BitmapFactory.decodeStream(is);
      //  Matrix matrix = new Matrix();
      //  int width = bitmap.getWidth();
      //  int height = bitmap.getHeight();
      //  matrix.postScale(3.5f, 3.5f);
      //  final Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
      //      width, height, matrix, true);
      //  String content = String.valueOf(index);
      //  SpannableString str = new SpannableString(String.valueOf(index));
      //  ImageSpan span = new ImageSpan(getContext(), resizedBitmap, ImageSpan.ALIGN_BASELINE);
      //  str.setSpan(span, 0, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      //  editText.append(str);
      //  is.close();
      //} catch (IOException e) {
      //
      //}

      final int index = currentItem * item_grid_num + position;
      AssetManager am = getContext().getAssets();

      DefaultGifEmoji defaultGifEmoji;
      if (index < EmoticonUtil.emoticonData.length) {
        defaultGifEmoji = new DefaultGifEmoji(am, String.format("emoticon/%d.gif", index),
            EmoticonUtil.emoticonData[index]);
      } else {
        defaultGifEmoji = new DefaultGifEmoji(am, String.format("emoticon/%d.gif", index),
            String.format("emoticon/%d.gif", index));
      }

      Drawable gifDrawable = defaultGifEmoji.getDrawable(getContext());
      ImageSpan imageSpan = new EqualHeightSpan(gifDrawable);

      editText.insertSpecialStr("" + index, false,
          "", imageSpan);
    } else {
      // 自定义表情
      StringBuffer sf = new StringBuffer();
      sf.append(CustomMessageType.CUSTOMFACE_TYPE);
      sf.append(iconNames.get(currentItem * item_grid_num + position));
      chatView.sendCustonFace(sf.toString());
    }
  }

  private void onFaceLongClick(int position) {
    int currentTab = mTabLayout.getCurrentTab();
    int currentItem = mViewPager.getCurrentItem();

    if (currentTab == 1) {
      //  添加到图片表情 才有长按操作
      new BottomSelectDialog().create(getContext(), "删除",
          v -> {

            String uuid = iconNames.get(currentItem * item_grid_num + position);
            String facePaths =
                (String) SPUtils.get(MyApplication.getInstance(), SpKeyConstant.FACE_IMGAE_PATH_KEY,
                    "");
            if (!TextUtils.isEmpty(facePaths)) {
              List<String> paths = new ArrayList<>(Arrays.asList(facePaths.split(",")));
              paths.remove(uuid);
              StringBuffer sf = new StringBuffer();
              for (String str : paths) {
                if (sf.toString().length() != 0) sf.append(",");
                sf.append(str);
              }
              SPUtils.put(MyApplication.getInstance(), SpKeyConstant.FACE_IMGAE_PATH_KEY,
                  sf.toString());
              setFaceLayout(1);
            }

            BottomSelectDialog.dismiss();
          }).show();
    }
  }

  /**
   * Called when a view has been clicked.
   *
   * @param v The view that was clicked.
   */
  @Override
  public void onClick(View v) {
    Activity activity = (Activity) getContext();
    int id = v.getId();
    if (id == R.id.btn_send) {
      chatView.sendText();
    }
    if (id == R.id.btn_add) {
      updateView(inputMode == InputMode.MORE ? InputMode.TEXT : InputMode.MORE);
    }
    if (id == R.id.btn_photo) {
      if (activity != null && requestCamera(activity)) {
        chatView.sendPhoto();
      }
    }
    if (id == R.id.btn_image) {
      if (activity != null && requestStorage(activity)) {
        chatView.sendImage();
      }
    }
    if (id == R.id.btn_voice) {

      new RxPermissions((FragmentActivity) activity).request(Manifest.permission.RECORD_AUDIO)
          .subscribe(new Observer<Boolean>() {
            @Override public void onSubscribe(Disposable d) {

            }

            @Override public void onNext(Boolean aBoolean) {
              if (aBoolean) {
                if (activity != null && requestAudio(activity)) {
                  updateView(InputMode.VOICE);
                }
              } else {
                Toast.makeText(activity, "你已拒绝录音权限，无法使用该功能", Toast.LENGTH_SHORT).show();
              }
            }

            @Override public void onError(Throwable e) {

            }

            @Override public void onComplete() {

            }
          });
    }
    if (id == R.id.btn_keyboard) {
      updateView(InputMode.TEXT);
    }
    if (id == R.id.btn_video) {
      if (getContext() instanceof FragmentActivity) {
        FragmentActivity fragmentActivity = (FragmentActivity) getContext();
        if (requestVideo(fragmentActivity)) {
          //                    VideoInputDialog.show(fragmentActivity.getSupportFragmentManager());
          if (requestRtmp()) {
            chatView.videoAction();
          } else {
            Toast.makeText(activity, "系统版本太低", Toast.LENGTH_SHORT).show();
          }
        }
      }
    }
    if (id == R.id.btnEmoticon) {
      updateView(inputMode == InputMode.EMOTICON ? InputMode.TEXT : InputMode.EMOTICON);
    }
    if (id == R.id.btn_money) {
      chatView.sendRedPackets();
    }
    if (id == R.id.btn_namecard) {
      chatView.sendBusinessCard();
    }
  }

  /**
   * 获取输入框文字
   */
  public Editable getText() {
    return editText.getText();
  }

  /**
   * 设置输入框文字
   */
  public void setText(String text) {
    editText.setText(text);
  }

  /**
   * 设置输入模式
   */
  public void setInputMode(InputMode mode) {
    updateView(mode);
  }

  /**
   * @param isGroup 群聊显示名片，单聊不显示
   */
  public void isGroup(boolean isGroup) {
    if (isGroup) {
      mBtnNamecard.setVisibility(VISIBLE);
    } else {
      mBtnNamecard.setVisibility(INVISIBLE);
    }
  }

  public enum InputMode {
    TEXT,
    VOICE,
    EMOTICON,
    MORE,
    VIDEO,
    NONE,
  }

  private boolean requestRtmp() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
  }

  private boolean requestVideo(Activity activity) {
    if (afterM()) {
      final List<String> permissionsList = new ArrayList<>();
      if ((activity.checkSelfPermission(Manifest.permission.CAMERA)
          != PackageManager.PERMISSION_GRANTED)) {
        permissionsList.add(Manifest.permission.CAMERA);
      }
      if ((activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO)
          != PackageManager.PERMISSION_GRANTED)) {
        permissionsList.add(Manifest.permission.RECORD_AUDIO);
      }
      if (permissionsList.size() != 0) {
        activity.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
            REQUEST_CODE_ASK_PERMISSIONS);
        return false;
      }
      int hasPermission = activity.checkSelfPermission(Manifest.permission.CAMERA);
      if (hasPermission != PackageManager.PERMISSION_GRANTED) {
        activity.requestPermissions(new String[] { Manifest.permission.CAMERA },
            REQUEST_CODE_ASK_PERMISSIONS);
        return false;
      }
    }
    return true;
  }

  private boolean requestCamera(Activity activity) {
    if (afterM()) {
      int hasPermission = activity.checkSelfPermission(Manifest.permission.CAMERA);
      if (hasPermission != PackageManager.PERMISSION_GRANTED) {
        activity.requestPermissions(new String[] { Manifest.permission.CAMERA },
            REQUEST_CODE_ASK_PERMISSIONS);
        return false;
      }
    }
    return true;
  }

  private boolean requestAudio(Activity activity) {
    if (afterM()) {
      int hasPermission = activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO);
      if (hasPermission != PackageManager.PERMISSION_GRANTED) {
        activity.requestPermissions(new String[] { Manifest.permission.RECORD_AUDIO },
            REQUEST_CODE_ASK_PERMISSIONS);
        return false;
      }
    }
    return true;
  }

  public boolean isShowPanel() {
    return morePanel.getVisibility() == VISIBLE || emoticonPanel.getVisibility() == VISIBLE;
  }

  private boolean requestStorage(Activity activity) {
    if (afterM()) {
      int hasPermission = activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
      if (hasPermission != PackageManager.PERMISSION_GRANTED) {
        activity.requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
            REQUEST_CODE_ASK_PERMISSIONS);
        return false;
      }
    }
    return true;
  }

  private boolean afterM() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
  }

  /**
   * 添加图片到表情，如果此时处于保存到图片表情tab，则刷新
   */
  public void addImgFace(){
    if (null != mTabLayout && mTabLayout.getCurrentTab() == 1){

      new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override public void run() {
          setFaceLayout(1);
        }
      },500);
    }
  }

}
